package datautils;

import org.apache.log4j.Logger;
import org.w3c.dom.*;
import questionanswer.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.util.LinkedList;
import java.util.List;
import javax.xml.xpath.*;

/**
 * Created with IntelliJ IDEA.
 * User: Инесса
 * Date: 21.11.13
 * Time: 23:31
 * To change this template use File | Settings | File Templates.
 */
public class XMLQuestionSourceXPath {

    private final String PATH = "questions.xml";
    private static final Logger logger = Logger.getLogger(XMLQuestionSource.class);

    public List<Question> getQuestions() {
        List<Question> questions = new LinkedList<>();
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(PATH);

            XPathFactory xFactory = XPathFactory.newInstance();
            XPath xpath = xFactory.newXPath();
            NodeList questionNodes = (NodeList) xpath.evaluate("//question", document, XPathConstants.NODESET);

            for (int i = 1; i <= questionNodes.getLength(); i++) {

                String expr = "//question["+i+"]/questionText";
                Node questionTextNode = (Node) xpath.evaluate(expr, document, XPathConstants.NODE);
                String questionText = questionTextNode.getTextContent();

                expr = "//question["+i+"]/theme";
                Node themeNode = (Node) xpath.evaluate(expr, document, XPathConstants.NODE);
                String theme = themeNode.getTextContent();

                expr = "//question["+i+"]/answer/answerVariant";
                NodeList answerVariants = (NodeList) xpath.evaluate(expr, document, XPathConstants.NODESET);

                expr = "//question["+i+"]/answer/answerVariant[@correct='true']";
                NodeList keyAnswers = (NodeList) xpath.evaluate(expr, document, XPathConstants.NODESET);

                questions.add(createQuestion(questionText,theme,toStringArray(keyAnswers),toStringArray(answerVariants)));
            }
        } catch (Throwable e) {
            //logger.error("Can't process questions file.");
            // TODO think about rethrowing exception
        }
        return questions;
    }

    private Question createQuestion(String questionText, String theme, String[] keyAnswers, String[] answerVariants) {
        Answer answer;
        if (keyAnswers.length == 1 && answerVariants.length == 1) {
            answer = new OneAnswer(keyAnswers[0]);
        } else if (keyAnswers.length == 1 && answerVariants.length > 1) {
            answer = new OneAnswerFromMany(keyAnswers[0], answerVariants);
        } else {
            answer = new MultipleAnswer(keyAnswers, answerVariants);
        }
        return new Question(questionText, answer, theme);
    }

    private String[] toStringArray(NodeList list) {
        String[] strings = new String[list.getLength()];
        for (int i = 0; i < list.getLength(); ++i) {
            strings[i] = list.item(i).getTextContent();
        }
        return strings;
    }

    public static void main(String[] args){
        XMLQuestionSourceXPath ob = new XMLQuestionSourceXPath();
        List<Question> list1 = ob.getQuestions();
        for (int i=0; i< list1.size(); i++){
            System.out.println(list1.get(i));
        }

    }

}
